import { onLoad, onUnload } from '@dcloudio/uni-app'
import { getPageQuery } from '../mpHelper'

type PageInvokeEffect = {
  onInvoke: () => any
  onUnload: () => any
}
type PageOnLoadEffect = {
  onLoad: <TQuery extends Record<string, string | undefined>>(query: TQuery) => any
  onUnload: () => any
}
export type PageEffect = Partial<PageInvokeEffect & PageOnLoadEffect>
export type PageEffectOptions = {
  lazy?: boolean
}
export function usePageEffect(effect: PageEffect, options?: PageEffectOptions) {
  if (!options?.lazy) {
    effect.onInvoke?.()
    if (typeof effect.onLoad === 'function') {
      onLoad((query) => {
        effect.onLoad?.(query as Record<string, string | undefined>)
      })
    }
  }
  onUnload(() => effect.onUnload?.())
  return () => {
    effect.onInvoke?.()
    effect.onLoad?.(getPageQuery())
  }
}
